package cn.edu.cug.cs.gtl.plugins.catalog.tree;

import cn.edu.cug.cs.gtl.apis.ui.catalogtree.CatalogTree;
import cn.edu.cug.cs.gtl.apis.ui.tree.TreeNodeData;
import cn.edu.cug.cs.gtl.protos.DataGroup;
import cn.edu.cug.cs.gtl.protos.DataItem;
import cn.edu.cug.cs.gtl.utils.impl.DataItemManagerImpl;
import cn.edu.cug.cs.gtl.utils.postgresql.DataCatalogManager4Postgresql;
import cn.edu.cug.cs.gtl.utils.postgresql.DataGroupManager4Postgresql;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.BorderLayout;
import java.awt.event.*;
import java.sql.SQLException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Vector;

public class DBQueryDataItemDialog extends JFrame {
    ResourceBundle resourceBundle = ResourceBundle.getBundle("catalog-resource", Locale.getDefault());
    private JTextField itemNameField;
    private JTable table;
    private DefaultTableModel defaultTableModel;
    private JPopupMenu popupMenu;
    private JPanel panel;
    private List<DataItem> list;
    final int[] row = {0};

    public DBQueryDataItemDialog(CatalogTree tree) {
        panel = new JPanel(new BorderLayout());
        add(panel);

        initializeUI();
        initPopupMenu(tree);

        setTitle(resourceBundle.getString("DBQueryDataItemDialog.dataitem_query"));
        setSize(400, 300);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void initializeUI() {
        // 创建表格显示查询结果
        defaultTableModel = new DefaultTableModel();
        defaultTableModel.addColumn(resourceBundle.getString("DBQueryDataItemDialog.name"));
        defaultTableModel.addColumn(resourceBundle.getString("DBQueryDataItemDialog.alias"));
        defaultTableModel.addColumn(resourceBundle.getString("DBQueryDataItemDialog.description"));
        defaultTableModel.addColumn(resourceBundle.getString("DBQueryDataItemDialog.format"));

        table = new JTable(defaultTableModel);
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    row[0] = table.rowAtPoint(e.getPoint());
                    if (row[0] >= 0 && row[0] < table.getRowCount()) {
                        table.setRowSelectionInterval(row[0], row[0]);
                        popupMenu.show(e.getComponent(), e.getX(), e.getY());
                    }
                }
            }
        });

        // 创建输入框和查询按钮，并放置在一个面板上
        JPanel inputPanel = new JPanel();
        itemNameField = new JTextField(20);
        JButton queryButton = new JButton(resourceBundle.getString("DBQueryDataItemDialog.query"));
        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String itemName = itemNameField.getText();
                try {
                    list = new DataItemManagerImpl().getList(itemName);
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
                // 清空表格数据
                defaultTableModel.setRowCount(0);

                Vector<Vector<String>> Vec = new Vector<>();
                // 更新表格数据
                for (DataItem element : list) {
                    Vector<String> vec = new Vector<>();
                    vec.add(element.getName());
                    vec.add(element.getAlias());
                    vec.add(element.getDescription());
                    vec.add(element.getFormat());
                    Vec.add(vec);
                }
                for (Vector<String> row : Vec)
                    defaultTableModel.addRow(row);
            }
        });
        inputPanel.add(itemNameField);
        inputPanel.add(queryButton);

        panel.add(inputPanel, BorderLayout.NORTH);
        panel.add(new JScrollPane(table), BorderLayout.CENTER);
    }

    //初始化右键菜单
    private void initPopupMenu(CatalogTree tree) {
        popupMenu = new JPopupMenu();
        JMenuItem addItem = new JMenuItem(resourceBundle.getString("DBQueryDataItemDialog.add_this_dataitem"));
        addItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
//                用户选中的数据项不能是已经在已被挂载过的数据项
                DataItem childItem = list.get(row[0]);
                //添加到树中
                DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(new TreeNodeData(childItem, childItem.getAlias(), true), false);
                newNode.setAllowsChildren(true);

                DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel();
                treeModel.insertNodeInto(newNode, selectNode, selectNode.getChildCount());

                TreeNode[] nodes = treeModel.getPathToRoot(newNode);
                tree.scrollPathToVisible(new TreePath(nodes));

                DataGroup parentGroup = (DataGroup) ((TreeNodeData) (selectNode.getUserObject())).getRefObject();
                int order_id = selectNode.getChildCount();
                int gid = DataCatalogManager4Postgresql.getGroupIdFromName(parentGroup.getName());
                try {
                    new DataItemManagerImpl().updateDataItem(childItem, order_id, gid);
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        popupMenu.add(addItem);
    }
}

